package com.swift.bean;

import java.util.ArrayList;
import java.util.List;

import org.xutils.db.Selector;
import org.xutils.db.annotation.Column;
import org.xutils.db.table.TableEntity;
import org.xutils.ex.DbException;

import com.swift.base.ApplicationBase;

public abstract class EntityBase extends AutoTextBean{

	
    @Column(name = "id", autoGen = false, isId = true)
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    
    public static <T> T findInstance(Class<T> entityType, int id){
		T result = null;
		try {
			result = ApplicationBase.DbContext.findById(entityType, id);
		} catch (DbException e) {			
			e.printStackTrace();
		}
		return result;
	}
    
    public static <T> List<T> findAllInstances(Class<T> entityType){
		 return findAllInstances(getSelector(entityType), false);	
    }
	
	public static Boolean updateInstance(Object instance, String... updateColumnNames){
		Boolean result = false;
		try {
			ApplicationBase.DbContext.update(instance, updateColumnNames);
			result = true;
		} catch (DbException e) {			
			e.printStackTrace();
		}
		return result;
	}
	
	 public static <T> List<T> findAllInstances(Selector<T> selector,  boolean customOrder){
	    	List<T> result = null;
			try {
				Selector<T> thisSelector = selector;
				if (!customOrder){
					thisSelector.orderBy("id", true);
				}
				//result = ApplicationBase.DbContext.findAll(thisSelector);
				result = thisSelector.findAll();
				if (result == null){
					result = new ArrayList<T>();
				}
			} catch (DbException e) {			
				e.printStackTrace();
			}
			return result;
	    }
	 
	 public static <T> Selector<T> getSelector(Class<T> entityType){
		 try {
			return  ApplicationBase.DbContext.selector(entityType);
		} catch (DbException e) {
			e.printStackTrace();
			return null;
		}
	 }
	 
	 public static <T> boolean tableIsExist(Class<T> entityType){
		TableEntity<T> table;
		try {
			table = ApplicationBase.DbContext.getTable(entityType);
			return table.tableIsExist();	
		} catch (DbException e) {
			e.printStackTrace();
		}
		return false;	
	 }
	 
	 /*原方法createTableIfNotExist被保护，只好用这笨方法或反射*/
	 public static <T> void createTableIfNotExist(Class<T> entityType){
		    if (!tableIsExist(entityType)){
				try {
					TableEntity<T> table = ApplicationBase.DbContext.getTable(entityType);
					T entity = table.createEntity();
					ApplicationBase.DbContext.save(entity); 
					ApplicationBase.DbContext.delete(entity);
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    }
	 }
}
